//文章列表

<template>
  <div class="publish-article-container">
    <h2>发布新文章</h2>
    <el-form @submit.prevent="publishArticle" class="publish-form">
      <el-form-item label="文章标题">
        <el-input v-model="articleTitle" placeholder="请输入文章标题..." />
      </el-form-item>
      <el-form-item label="文章内容">
        <el-input
          v-model="articleBody"
          type="textarea"
          :rows="10"
          placeholder="请输入文章内容..."
        />
      </el-form-item>
      <el-form-item label="是否完成">
        <el-switch v-model="completed" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="publishArticle" :loading="loading">发布</el-button>
      </el-form-item>
    </el-form>
    <div v-if="message" :class="{ 'success-message': isSuccess, 'error-message': !isSuccess }">{{ message }}</div>
    <el-button v-if="isSuccess" type="info" @click="router.push('/articles')" class="back-to-list-button">返回文章列表</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router'; // 导入 useRouter

const userStore = useUserStore();
const articleTitle = ref(''); // 新增标题字段
const articleBody = ref('');
const completed = ref(false); // 新增完成状态字段
const loading = ref(false);
const message = ref('');
const isSuccess = ref(false);
const router = useRouter(); // 获取 router 实例

// 获取下一个可用的 articleid
const getNextArticleId = async (): Promise<number> => {
  try {
    const response = await fetch('/api/demo/getallitems');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data) && data.length > 0) {
      const maxId = Math.max(...data.map(item => item.id));
      return maxId + 1;
    } else {
      return 1; // 如果没有文章，从1开始
    }
  } catch (e: any) {
    console.error('获取文章列表失败:', e);
    ElMessage.error('获取文章ID失败，请稍后再试。');
    return 0; // 返回0表示获取失败，阻止发布
  }
};

const publishArticle = async () => {
  if (!articleTitle.value.trim() || !articleBody.value.trim()) {
    ElMessage.warning('标题和内容不能为空！');
    return;
  }

  const userId = userStore.currentUserId;
  if (!userId) {
    ElMessage.error('用户未登录，无法发布文章。');
    router.push('/login');
    return;
  }

  loading.value = true;
  
  try {
    const response = await fetch('/api/demo/additem', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: articleTitle.value,
        body: articleBody.value,
        userid: userId,
        completed: completed.value
      }),
    });

    const result = await response.json();

    // 修改成功判断逻辑：检查响应中是否包含 'id' 字段
    if (result.id) {
      isSuccess.value = true;
      message.value = '文章发布成功！';
      articleBody.value = ''; // 清空输入框
      articleTitle.value = ''; // 清空标题输入框
      completed.value = false; // 重置完成状态
      // 移除自动跳转，改为显示按钮让用户点击跳转
    } else {
      isSuccess.value = false;
      message.value = result.message || '文章发布失败，请重试。';
    }
  } catch (e: any) {
    isSuccess.value = false;
    message.value = '网络错误或服务器无响应: ' + e.message;
    console.error('发布文章失败:', e);
  } finally {
    loading.value = false;
  }
};

// 可以在组件加载时预先获取一次文章ID，或者只在发布时获取
// onMounted(() => {
//   // 如果需要，可以在这里调用 getNextArticleId()
// });
</script>

<style scoped>
.publish-article-container {
  max-width: 700px;
  margin: 50px auto;
  padding: 30px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 35px;
  font-size: 2.5em;
  font-weight: 700;
  letter-spacing: 1px;
}

.publish-form .el-form-item {
  margin-bottom: 25px;
}

.publish-form .el-form-item label {
  font-size: 1.1em;
  color: #555;
  margin-bottom: 8px;
}

.publish-form .el-textarea__inner {
  min-height: 200px !important;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  padding: 15px;
  font-size: 1em;
  transition: border-color 0.3s ease;
}

.publish-form .el-textarea__inner:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.15);
}

.publish-form .el-button {
  width: 100%;
  padding: 12px 0;
  font-size: 1.2em;
  border-radius: 8px;
  background-color: #007bff;
  border-color: #007bff;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.publish-form .el-button:hover {
  background-color: #0056b3;
  border-color: #0056b3;
}

.message {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  font-size: 1em;
  text-align: center;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.back-to-list-button {
  margin-top: 20px;
  width: 100%;
}
</style>